package com.papercutting.platform.controller;

import com.papercutting.platform.common.Result;
import com.papercutting.platform.dto.response.UserStudyResponse;
import com.papercutting.platform.entity.UserStudy;
import com.papercutting.platform.service.UserStudyService;
import com.papercutting.platform.util.SecurityUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * 用户学习记录控制器
 */
@RestController
@RequestMapping("/api/study")
@RequiredArgsConstructor
public class UserStudyController {
    
    private final UserStudyService userStudyService;
    
    /**
     * 获取用户学习记录列表
     */
    @GetMapping("/list")
    public Result<Map<String, Object>> getStudyRecords(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(defaultValue = "createTime") String orderBy) {
        
        // 从Security上下文中获取当前用户ID
        Long userId = SecurityUtils.getCurrentUserId();
        
        // 创建分页对象
        Sort sort = Sort.by(Sort.Direction.DESC, orderBy);
        Pageable pageable = PageRequest.of(page - 1, size, sort);
        
        // 查询数据（包含教程信息）
        Page<UserStudyResponse> studyPage = userStudyService.findUserStudyListWithTutorial(userId, pageable);
        
        // 构造返回结果
        Map<String, Object> result = new HashMap<>();
        result.put("list", studyPage.getContent());
        result.put("total", studyPage.getTotalElements());
        result.put("page", page);
        result.put("size", size);
        result.put("totalPages", studyPage.getTotalPages());
        
        return Result.success(result);
    }
    
    /**
     * 获取学习记录详情
     */
    @GetMapping("/{id}")
    public Result<UserStudy> getStudyRecordDetail(@PathVariable Long id) {
        UserStudy studyRecord = userStudyService.findById(id);
        if (studyRecord == null) {
            return Result.error(404, "学习记录不存在");
        }
        return Result.success(studyRecord);
    }
    
    /**
     * 创建或更新学习记录
     */
    @PostMapping("/record")
    public Result<UserStudy> saveStudyRecord(@RequestBody UserStudy studyRecord) {
        
        // 从Security上下文中获取当前用户ID
        Long userId = SecurityUtils.getCurrentUserId();
        
        // 查找是否已存在学习记录
        UserStudy existingRecord = userStudyService.findByUserIdAndTutorialId(userId, studyRecord.getTutorialId());
        
        if (existingRecord != null) {
            // 更新现有记录
            existingRecord.setProgress(studyRecord.getProgress());
            existingRecord.setCurrentStep(studyRecord.getCurrentStep());
            existingRecord.setTotalSteps(studyRecord.getTotalSteps());
            existingRecord.setStudyDuration(studyRecord.getStudyDuration());
            existingRecord.setIsCompleted(studyRecord.getIsCompleted());
            existingRecord.setCompletedTime(studyRecord.getCompletedTime());
            existingRecord.setLastStudyTime(LocalDateTime.now());
            existingRecord.setUpdateTime(LocalDateTime.now());
            
            UserStudy savedRecord = userStudyService.save(existingRecord);
            return Result.success(savedRecord);
        } else {
            // 创建新记录
            studyRecord.setUserId(userId);
            studyRecord.setCreateTime(LocalDateTime.now());
            studyRecord.setUpdateTime(LocalDateTime.now());
            studyRecord.setLastStudyTime(LocalDateTime.now());
            
            UserStudy savedRecord = userStudyService.save(studyRecord);
            return Result.success(savedRecord);
        }
    }
    
    /**
     * 获取用户学习进度统计
     */
    @GetMapping("/progress")
    public Result<Map<String, Object>> getStudyProgress() {
        // 从Security上下文中获取当前用户ID
        Long userId = SecurityUtils.getCurrentUserId();
        
        return Result.success(userStudyService.getStudyProgress(userId));
    }
    
    /**
     * 获取特定教程的学习记录
     */
    @GetMapping("/tutorial/{tutorialId}")
    public Result<UserStudy> getTutorialStudyRecord(@PathVariable Long tutorialId) {
        Long userId = SecurityUtils.getCurrentUserId();
        UserStudy studyRecord = userStudyService.findByUserIdAndTutorialId(userId, tutorialId);
        
        if (studyRecord == null) {
            // 返回默认的学习记录
            UserStudy defaultRecord = new UserStudy();
            defaultRecord.setUserId(userId);
            defaultRecord.setTutorialId(tutorialId);
            defaultRecord.setProgress(0);
            defaultRecord.setCurrentStep(1);
            defaultRecord.setTotalSteps(0);
            defaultRecord.setStudyDuration(0);
            defaultRecord.setIsCompleted(false);
            return Result.success(defaultRecord);
        }
        
        return Result.success(studyRecord);
    }
    
    /**
     * 删除学习记录
     */
    @DeleteMapping("/{id}")
    public Result<Void> deleteStudyRecord(@PathVariable Long id) {
        Long userId = SecurityUtils.getCurrentUserId();
        UserStudy studyRecord = userStudyService.findById(id);
        
        if (studyRecord == null) {
            return Result.error(404, "学习记录不存在");
        }
        
        // 检查学习记录是否属于当前用户
        if (!studyRecord.getUserId().equals(userId)) {
            return Result.error(403, "无权删除此学习记录");
        }
        
        userStudyService.deleteById(id);
        return Result.success();
    }
    
    /**
     * 批量删除学习记录
     */
    @DeleteMapping("/batch")
    public Result<Void> batchDeleteStudyRecords(@RequestBody java.util.List<Long> ids) {
        Long userId = SecurityUtils.getCurrentUserId();
        
        for (Long id : ids) {
            UserStudy studyRecord = userStudyService.findById(id);
            if (studyRecord != null && studyRecord.getUserId().equals(userId)) {
                userStudyService.deleteById(id);
            }
        }
        
        return Result.success();
    }
}